package com.supcalls.tool;

import java.util.concurrent.*;

/**
 * CyclicBarrier 允许一组线程互相等待，直到所有线程都到达某个公共屏障点。
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(3, () -> {
            System.out.println("All threads reached the barrier. Proceeding with the next task.");
        });

        for (int i = 0; i < 3; i++) {
            final int taskId = i;
            new Thread(() -> {
                try {
                    System.out.println("Thread " + taskId + " is doing its work.");
                    Thread.sleep(2000);
                    System.out.println("Thread " + taskId + " reached the barrier.");
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
